<?php
namespace Destroyer\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Destroyer\Models\Menu;
use Destroyer\Http\Requests\MenuCreateRequest;

class MenuController extends Controller
{

	/**
	 * @path /api/system/user
	 */
	public function index(Request $request)
	{
		$models = Menu::query()->orderBy('sort')->get();

		$menuTree = buildTree($models->toArray(), 0);

		return response()->admin($menuTree);
	}

	public function store(MenuCreateRequest $request)
	{
		$model = Menu::create($request->all());

		if( $model && $model->type=='M' ){
			$actions = [
	            ['parent_id' => $model->id, 'type'  => 'B', 'sort'=> 1, 'title' => '列表', 'code'  => "{$model->code}.index", 'is_hidden'=>'1'],
	            ['parent_id' => $model->id, 'type'  => 'B', 'sort'=> 2, 'title' => '新增', 'code'  => "{$model->code}.store", 'is_hidden'=>'1'],
	            ['parent_id' => $model->id, 'type'  => 'B', 'sort'=> 3, 'title' => '编辑', 'code'  => "{$model->code}.update", 'is_hidden'=>'1'],
	            ['parent_id' => $model->id, 'type'  => 'B', 'sort'=> 4, 'title' => '删除', 'code'  => "{$model->code}.destroy", 'is_hidden'=>'1'],
	            ['parent_id' => $model->id, 'type'  => 'B', 'sort'=> 5, 'title' => '回收站', 'code'  => "{$model->code}.trashed", 'is_hidden'=>'1'],
	            ['parent_id' => $model->id, 'type'  => 'B', 'sort'=> 6, 'title' => '恢复数据', 'code'  => "{$model->code}.restore", 'is_hidden'=>'1'],
	            ['parent_id' => $model->id, 'type'  => 'B', 'sort'=> 7, 'title' => '物理删除', 'code'  => "{$model->code}.delete", 'is_hidden'=>'1'],
			];

			Menu::upsert($actions, [], null);
		}

		return response()->admin($model);
	}

	/**
	 * @path /api/system/user/1
	 */
	public function show(Request $request, $id)
	{
		$model = Menu::findOrFail($id);

		return response()->admin($model);
	}

	public function update(Request $request, $id)
	{
		$model = Menu::findOrFail($id);

		$data = $request->all();
		unset($data['role_ids']);
		$model->forceFill($data)->save();

		return response()->admin($model);
	}

	public function destroy(Request $request, $id)
	{

	}
}
